from django.shortcuts import render, redirect, reverse
from django.urls.base import reverse_lazy
from django.contrib.auth.decorators import login_required
from .models import BlogCategory, Blog, BlogComment
from django.views.decorators.http import require_http_methods, require_GET, require_POST
from .forms import PubBlogForm
import math
from django.db.models import Q

# Create your views here.

@require_GET
def index(request):
    blogs = Blog.objects.all()
    blog_categories = BlogCategory.objects.all()
    return render(request, 'index.html', context={'blogs': blogs[:6], 'blog_category': blog_categories})


def articles(request, page_id):
    blogs = Blog.objects.all()

    left = (page_id - 1) * 5
    right = (page_id - 1) * 5 + 4

    length = len(blogs)
    time = math.ceil(length / 5)
    pages = [i for i in range(1, time + 1)]
    return render(request, 'articles.html', context={'blogs': blogs[left:right + 1], 'pages': pages, 'page_id': page_id})


@require_GET
def detail(request, blog_id):
    blog = Blog.objects.get(pk=blog_id)
    return render(request, 'detail.html', context={'blog': blog})



@require_http_methods(['GET', 'POST'])
@login_required(login_url=reverse_lazy('myauth:login'))
def blog_pub(request):
    if request.method == 'GET':
        categories = BlogCategory.objects.all()
        return render(request, 'pub_blog.html', context={'categories': categories})
    else:
        form = PubBlogForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            category_id = form.cleaned_data.get('category')
            content =form.cleaned_data.get('content')
            blog = Blog.objects.create(title=title, content=content, category_id=category_id, author=request.user)
            return redirect(reverse('blog:detail', kwargs={'blog_id': blog.pk}))
        else:
            print(form.errors)
            categories = BlogCategory.objects.all()
            return render(request, 'pub_blog.html', context={'categories': categories})

@require_POST
@login_required(login_url=reverse_lazy('myauth:login'))
def pub_comment(request):
    blog_id = request.POST.get('blog_id')
    content = request.POST.get('content')
    BlogComment.objects.create(content=content, blog_id=blog_id, author=request.user)
    return redirect(reverse('blog:detail', kwargs={'blog_id': blog_id}))

@require_GET
def search(request):
    #查询字符串的形式
    #/search?q=xxx
    q = request.GET.get('q')
    #查找相关的博客
    blogs = Blog.objects.filter(Q(title__icontains=q)|Q(content__icontains=q)).all()
    blog_categories = BlogCategory.objects.all()
    return render(request, 'index.html', context={'blogs': blogs, 'blog_categories': blog_categories})






